package com.vgemv.jsutilitysdk.geometry;

import android.app.Activity;
import android.content.Context;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.util.DisplayMetrics;
import android.util.Size;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.widget.ContentFrameLayout;

import com.vgemv.jsutilitysdk.log.JsLogManager;

public class JsGeometryManager {
    public static Context mContext;
    private static JsGeometryManager _sharedInstance;
    //缓存像素密度
    public static Float mF_dpi;

    public static TextView mtv;

    public static void initClass(Context context) {
        _sharedInstance = new JsGeometryManager();
        mContext = context;
    }


    static public  int pixelFromDp(float dp) {
        return pixelFromDp(dp,mContext);
    }

    /**
     * getScreenSizeInPixel
     * 返回屏幕的完整大小.
     * @param context
     * @return
     */
    public static Size getScreenSizeInPixel(Context context) {
        WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
        Point point = new Point(0,0);
        wm.getDefaultDisplay().getRealSize(point);
        Size size = new Size(point.x,point.y);
        return size;
    }

    public static Size getScreenSizeInPixel() {
        return getScreenSizeInPixel(mContext);
    }

    /**
     * getDeviceSafeAreaSizeInPixel
     * 获取屏幕安全区域的size
     * Todo: 如何获取top的padding 和bottom的padding?
     * TopBaddiding
     * @param context
     * @return
     */
    public static Rect getScreenSafeAreaFrameInPixel(Context context) {
        //获取设备尺寸

        WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);

//        DisplayMetrics dm = new DisplayMetrics();
        Rect safeAreaBounds = new Rect();
        wm.getDefaultDisplay().getRectSize(safeAreaBounds);

//        int width = dm.widthPixels;         // 屏幕宽度（像素）
//        int height = dm.heightPixels;       // 屏幕高度（像素）
//        float density = dm.density;         // 屏幕密度（0.75 / 1.0 / 1.5）
//        int densityDpi = dm.densityDpi;     // 屏幕密度dpi（120 / 160 / 240）
//        // 屏幕宽度算法:屏幕宽度（像素）/屏幕密度
////        int screenWidth = (int) (width / density);  // 屏幕宽度(dp)
////        int screenHeight = (int) (height / density);//
        return safeAreaBounds;
    }


    //Activity的R.id.contentView的top在screen的位置
    public static int contentFrameLayoutTopInScreen(Activity activity) {
        return contentFrameLayoutFrameInScreen(activity).top;
    }
    public static Rect contentFrameLayoutFrameInScreen(Activity activity) {
        Window phoneWindow = activity.getWindow();
        ViewGroup vp = (ViewGroup)phoneWindow.getDecorView();
        ContentFrameLayout contentFrameLayout = vp.findViewById(android.R.id.content);
        Rect frame = new Rect();
        contentFrameLayout.getGlobalVisibleRect(frame);
        return frame;
    }

    public static Rect getScreenSafeAreaFrameInPixel() {
        return getScreenSafeAreaFrameInPixel(mContext);
    }

    public static Size getScreenSafeAreaSizeInPixel() {
        WindowManager wm = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
        Rect safeAreaBounds = new Rect();
        wm.getDefaultDisplay().getRectSize(safeAreaBounds);
        return new Size(safeAreaBounds.width(),safeAreaBounds.height());
    }

    //这个方法在onCreate时,也不能获取到正确的数据,感觉和
    public static Rect getActivityRootViewFrame(Activity activity) {
        Rect frame = new Rect();
        Window activityPhoneWindow = activity.getWindow();
        View decorView = activityPhoneWindow.getDecorView();
        ContentFrameLayout contentView = (ContentFrameLayout)decorView.findViewById(android.R.id.content);
        contentView.getGlobalVisibleRect(frame);
        return frame;
    }


    public static void checkScreenInfo(Activity activity) {
        Rect rect = new Rect();

        //WindowService.window
        int screenHeight = JsGeometryManager.getScreenSizeInPixel().getHeight();
        JsLogManager.logc_d("JsGeometryManager","WindowServcie window height is %d",screenHeight);
        Window activityPhoneWindow = activity.getWindow();

        //DecorViewFrame
        View decorView = activityPhoneWindow.getDecorView();
        decorView.getGlobalVisibleRect(rect);
        JsLogManager.logc_d("JsGeometryManager","DecorViewFrame is %s",rect.toString());
        //DecorContentViewFrame
        final ViewGroup contentView = (ViewGroup)decorView.findViewById(android.R.id.content);
        contentView.getGlobalVisibleRect(rect);
        JsLogManager.logc_d("JsGeometryManager","DecorContentViewFrame is %s",rect.toString());

        //ActivityContentViewFrame
        ViewGroup activityContentView = (ViewGroup)contentView.getChildAt(0);
        activityContentView.getGlobalVisibleRect(rect);
        JsLogManager.logc_d("JsGeometryManager","ActivityContentViewFrame is %s",rect.toString());

        //感觉windowManager得到的height都是不对的.
        Point point = new Point(0,0);
//                getWindowManager().getDefaultDisplay().getSize(point);
        activity.getWindowManager().getDefaultDisplay().getRealSize(point);
        int activityWindowManagerHeight = point.y;
        JsLogManager.logc_d("JsGeometryManager","Activity window manager height is %d",activityWindowManagerHeight);

        Rect safeAresFrame = JsGeometryManager.getScreenSafeAreaFrameInPixel();
        JsLogManager.logc_d("JsGeometryManager","Screen safe area frame is %s",safeAresFrame.toString());

        int notchHeight = JsGeometryManager.getNotchHeight();
        JsLogManager.logc_d("JsGeometryManager","Notch height is %d",notchHeight);
    }


    /**
     * 模拟器,2.625
     * 小米11,3.5
     * 小米8SE,2.7
     * @param dp
     * @param context
     * @return
     */
    public static int pixelFromDp(float dp, Context context) {
        if(mF_dpi == null) {
            WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            DisplayMetrics dm = new DisplayMetrics();
            wm.getDefaultDisplay().getMetrics(dm);
            mF_dpi = dm.density;
        }
        int pixel = (int) (dp * mF_dpi);
        return pixel;
    }


    /**
     * 获取刘海高度
     * @param
     * @return
     */
    public static int getNotchHeight() {
        return getNotchHeight(mContext);
    }
    public static int getNotchHeight(Context context) {
        int resourceId = context.getResources().getIdentifier("notch_height", "dimen", "android");
        if (resourceId > 0) {
            return context.getResources().getDimensionPixelSize(resourceId);
        }
        return 0;
    }

    /*
    @Override
 public boolean hasNotch(Activity activity) {
     boolean ret = false;
     try {
         ret = activity.getPackageManager().hasSystemFeature("com.oppo.feature.screen.heteromorphism");
     } catch (Throwable ignore) {
     }
     return ret;
 }

 获取刘海的左上角和右下角的坐标
private static String getScreenValue() {
     String value = "";
     Class<?> cls;
     try {
         cls = Class.forName("android.os.SystemProperties");
         Method get = cls.getMethod("get", String.class);
         Object object = cls.newInstance();
         value = (String) get.invoke(object, "ro.oppo.screen.heteromorphism");
     } catch (Throwable ignore) {
     }
     return value;
 }
     */




    /**
     * 计算单行文本的尺寸
     */
    public static int getOneLineTextHeight(Context context,String content,float textSizeInSp) {
        Paint pFont = new Paint();
        int textSizeInPixel = sp2px(context,textSizeInSp);
        pFont.setTextSize(textSizeInPixel);
        Rect rect = new Rect();
        pFont.getTextBounds(content, 0, content.length(), rect);
        return rect.height();
    }

    /**
     * 计算单行文本宽度
     */
    public static int getOneLineTextWidth(Context context,String content,float textSizeInSp) {
        Paint pFont = new Paint();
        int textSizeInPixel = sp2px(context,textSizeInSp);
        pFont.setTextSize(textSizeInPixel);
        Rect rect = new Rect();
//        pFont.getTextBounds(content, 0, content.length(), rect);
        int width = (int)pFont.measureText(content);
        return width;
    }
    /**
     * 计算单行文本宽度
     */
    public static int getOneLineTextWidth(String content,float textSizeInSp) {
        return getOneLineTextWidth(mContext,content,textSizeInSp);
    }

    public static Size getOneLineTextSize(String content,float textSizeInSp) {
        if(mtv == null) {
            mtv = new TextView(mContext);

        }
        int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE, View.MeasureSpec.AT_MOST);
        int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE, View.MeasureSpec.AT_MOST);
        mtv.setText(content);
        float textSizeInPixel = sp2px(mContext,textSizeInSp);
        mtv.setTextSize(textSizeInPixel);
        mtv.measure(widthMeasureSpec,heightMeasureSpec);
        Size size = new Size(mtv.getMeasuredWidth(),mtv.getMeasuredHeight());
        return size;

    }



    /**
     * 将sp值转换为px值
     *
     * @param spValue
     * @param fontScale
     *            （DisplayMetrics类中属性scaledDensity）
     * @return
     */
    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

/* Frame计算便捷方式 Start */
    // 1 全部是父视图
// 1.1
    public static Rect frameHAlignLeftVAlignTop(Size containerSize,Size size,Point offset) {
        int left = offset.x;
        int top = offset.y;
        int right = left + size.getWidth();
        int bottom = top + size.getHeight();
        return new Rect(left,top,right,bottom);
    }
// 1.2
    public static Rect frameHAlignCenterVAlignTop(Size containerSize,Size size,Point offset) { return new Rect();}
// 1.3
    public static Rect frameHAlignRightVAlignTop(Size containerSize,Size size,Point offset) { return new Rect();}

// 1.4
    public static Rect frameHAlignLeftVAlignCenter(Size containerSize, Size size, Point offset) {
        int left = offset.x;
        int top = (containerSize.getHeight() - size.getHeight())/2 + offset.y;
        int right = left + size.getWidth();
        int bottom = top + size.getHeight();
        return new Rect(left,top,right,bottom);
    }
// 1.5
    public static Rect frameHAlignCenterVAlignCenter(Size containerSize,Size size,Point offset) { return new Rect();}
// 1.6
    public static Rect frameHAlignRightVAlignCenter(Size containerSize,Size size,Point offset) { return new Rect();}

// 1.7
    public static Rect frameHAlignLeftVAlignBottom(Size containerSize,Size size,Point offset)  {
        int left = offset.x;
        int top = containerSize.getHeight() - size.getHeight() + offset.y;
        int right = left + size.getWidth();
        int bottom = top + size.getHeight();
        return new Rect(left,top,right,bottom);
    }
// 1.8
    public static Rect frameHAlignCenterVAlignBottom(Size containerSize,Size size,Point offset) { return new Rect();}
// 1.9
    public static Rect frameHAlignRightVAlignBottom(Size containerSize,Size size,Point offset) {
        int left = containerSize.getWidth() - size.getWidth() + offset.x;
        int top = containerSize.getHeight() - size.getHeight() + offset.y;
        int right = left + size.getWidth();
        int bottom = top + size.getHeight();
        return new Rect(left,top,right,bottom);
    }

// 2 全部是兄弟节点
// 2.1
    public static Rect frameHLeftVAbove(Size containerSize,Size size,Rect siblingFrame,Point offset) { return new Rect();}
// 2.2
    public static Rect frameHCenterVAbove(Size containerSize,Size size,Rect siblingFrame,Point offset) { return new Rect();}
// 2.3
    public static Rect frameHRightVAbove(Size containerSize,Size size,Rect siblingFrame,Point offset) { return new Rect();}

// 2.4
    public static Rect frameHLeftVCenter(Size containerSize,Size size,Rect siblingFrame,Point offset) { return new Rect();}
// 2.5
    public static Rect frameHCenterVCenter(Size containerSize,Size size,Rect siblingFrame,Point offset) { return new Rect();}
// 2.6
    public static Rect frameHRightVCenter(Size containerSize,Size size,Rect siblingFrame,Point offset) { return new Rect();}

// 2.7
    public static Rect frameHLeftVBelow(Size containerSize,Size size,Rect siblingFrame,Point offset) { return new Rect();}
// 2.8
    public static Rect frameHCenterVBelow(Size containerSize,Size size,Rect siblingFrame,Point offset) { return new Rect();}
// 2.9
    public static Rect frameHRightVBelow(Size containerSize,Size size,Rect siblingFrame,Point offset) { return new Rect();}


// 3 H水平参考父视图 V竖直参考兄弟
// 3.1
    public static Rect frameHAlignLeftVAbove(Size containerSize,Size size,Rect siblingFrame,Point offset) { return new Rect();}
// 3.2
    public static Rect frameHAlignCenterVAbove(Size containerSize,Size size,Rect siblingFrame,Point offset) { return new Rect();}
// 3.3
    public static Rect frameHAlignRightVAbove(Size containerSize,Size size,Rect siblingFrame,Point offset) { return new Rect();}

// 3.4
    public static Rect frameHAlignLeftVCenter(Size containerSize,Size size,Rect siblingFrame,Point offset) { return new Rect();}
// 3.5
    public static Rect frameHAlignCenterVCenter(Size containerSize,Size size,Rect siblingFrame,Point offset) { return new Rect();}
// 3.6
    public static Rect frameHAlignRightVCenter(Size containerSize,Size size,Rect siblingFrame,Point offset) { return new Rect();}

// 3.7
    public static Rect frameHAlignLeftVBelow(Size containerSize,Size size,Rect siblingFrame,Point offset) { return new Rect();}
// 3.8
    public static Rect frameHAlignCenterVBelow(Size containerSize,Size size,Rect siblingFrame,Point offset) { return new Rect();}
// 3.9
    public static Rect frameHAlignRightVBelow(Size containerSize,Size size,Rect siblingFrame,Point offset) { return new Rect();}



// 4 H水平参考兄弟 V竖直参考父视图
// 4.1
    public static Rect frameHLeftVAlignTop(Size containerSize,Size size,Rect siblingFrame,Point offset) { return new Rect();}
// 4.2
    public static Rect frameHCenterVAlignTop(Size containerSize,Size size,Rect siblingFrame,Point offset) { return new Rect();}
// 4.3
    public static Rect frameHRightVAlignTop(Size containerSize,Size size,Rect siblingFrame,Point offset) { return new Rect();}

// 4.4
    public static Rect frameHLeftVAlignCenter(Size containerSize,Size size,Rect siblingFrame,Point offset) { return new Rect();}
// 4.5
    public static Rect frameHCenterVAlignCenter(Size containerSize,Size size,Rect siblingFrame,Point offset) { return new Rect();}

    /**
     * 4.6
     * 计算frame
     */
    public static Rect frameHRightVAlignCenter(Size containerSize, Rect siblingFrame, Size size) {
        return frameHRightVAlignCenter(containerSize,siblingFrame,size,new Point(0,0));
    }
    public static Rect frameHRightVAlignCenter(Size containerSize, Rect siblingFrame, Size size, Point offset) {
        int left = siblingFrame.right + offset.x;
        int top = (containerSize.getHeight() - size.getHeight())/2 + offset.y;
        int right = left + size.getWidth();
        int bottom = top + size.getHeight();
        return new Rect(left,top,right,bottom);
    }
// 4.7
    public static Rect frameHLeftVAlignBottom(Size containerSize,Size size,Rect siblingFrame,Point offset) { return new Rect();}
// 4.8
    public static Rect frameHCenterVAlignBottom(Size containerSize,Size size,Rect siblingFrame,Point offset) { return new Rect();}
// 4.9
    public static Rect frameHRightVAlignBottom(Size containerSize,Size size,Rect siblingFrame,Point offset) { return new Rect();}

    /* Frame计算便捷方式 End */

    /* 为RelativeLayout设置布局参数 */

    public static void setRelativeFrame(Rect rect,View view,ViewGroup containerView) {
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(rect.width(),rect.height());
        lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        lp.setMargins(rect.left,rect.top,0,0);
        containerView.addView(view,lp);
    }
    public static void setRelativeFrame(Rect rect,View view,ViewGroup containerView,int index) {
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(rect.width(),rect.height());
        lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
        lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
        lp.setMargins(rect.left,rect.top,0,0);
        containerView.addView(view,index,lp);
    }

    /**
     * 将相对于屏幕的坐标转换为相对于view的坐标
     * @param pt_screen
     * @param view
     * @return
     */
    public static Point locationFromScreenToView(Point pt_screen,View view) {
        Point pt_view = new Point();
        int[] viewOrigin = new int[2];
        view.getLocationOnScreen(viewOrigin);
        int viewX = viewOrigin[0];
        int viewY = viewOrigin[1];
        pt_view.x = pt_screen.x - viewX;
        pt_view.y = pt_screen.y - viewY;
        return pt_view;
    }
}
